from app.db.mongoClient import ErrMongoClient, get_mongo_client
from . import dbSynPosUser, collectionUserRoleList
from app.settings.base import all_permission
from app.db import dbServerQuery

def rolePowerQuery(userRoleId):
    '''
    根据用户角色Id，查询该角色的权限
    '''
    try:
        mg_client = get_mongo_client()
        res = mg_client[dbSynPosUser][collectionUserRoleList].find_one({'roleId': userRoleId})
        if res is None:
            return False
        rolePower = []
        resRolePower = res.get('rolePower')
        # 去服务列表里找对应的接口名字
        allPower = dbServerQuery.queryRolePower()
        if allPower is not None:
            for key in resRolePower:
                for v in allPower:
                    if v == key:
                        dict = allPower[v]
                        rolePower.extend(dict.get('power'))

        return rolePower
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def rolePowerEdit(userRoleId, power):
    '''
    根据用户角色Id，编辑该角色的权限
    '''
    try:
        mg_client = get_mongo_client()
        collect = mg_client[dbSynPosUser][collectionUserRoleList]
        
        return collect.find_one_and_update({'roleId': userRoleId}, {'$set': {'rolePower': power}})
    except Exception as e:
        raise ErrMongoClient.data(str(e))
